#region Copyright & License
/* Tyng.Data
 * Copyright (c) 2007, Paul Tyng, All rights reserved.
 * Code licensed under the BSD License:
 * http://www.opensource.org/licenses/bsd-license.php
 * Downloaded from: http://code.google.com/p/tyngdata/
*/
#endregion

using System;
using System.ComponentModel;

namespace Tyng.Data
{
    /// <summary>
    /// Converts strings with a "%" symbol in them.
    /// </summary>
    public sealed class PercentageConverter : IFieldConverter
    {
        private const string PercentSign = "%";

        private PercentageConverter() { }

		#region IFieldConverter Members

        object IFieldConverter.ConvertFromString(Type toType, string data)
		{
            if (!string.IsNullOrEmpty(data))
            {
                if (data.EndsWith(PercentSign)) data = data.Substring(0, data.Length - 1);

                decimal d = decimal.Parse(data);

                d /= 100;
                
                DecimalConverter tc = new DecimalConverter();

                return tc.ConvertTo(d, toType);
            }

            throw new InvalidCastException();
		}

		#endregion

        private static PercentageConverter _default;

        /// <summary>
        /// The default instance of the converter.
        /// </summary>
        public static PercentageConverter Default 
		{ 
			get 
			{ 
				if(_default == null)
                    _default = new PercentageConverter();

				return _default; 
			} 
		}
    }
}
